<style lang="scss" src="./index.scss" scoped></style>
<template>
    <main class="form-main">
        <section class="form-drag-box">
            <div class="form-main__body custom-form">
                <div
                    class="custom-control-box"
                    :class="{ centerBox: _isReadOnly }"
                >
                    <div class="other-tag-list" v-if="!_isReadOnly">
                        <div class="creat-node-model" @click="maskShow">
                            <div class="slide1"></div>
                            <div class="slide2"></div>
                            <div class="slide3"></div>
                            <span>
                                一键生成>>
                                <img
                                    src="@/assets/create-form-icon.png"
                                    alt=""
                                />
                            </span>
                        </div>
                        <div class="creat-node-normal">
                            <span class="title">智能快速创建</span>
                            <drag-list
                                :list="otherTagList"
                                @batchAdd="batchAdd"
                                @batchImport="batchImport"
                                @item-click="handleItemClick"
                            ></drag-list>
                        </div>
                        <div class="creat-node-type">
                            <span class="title">单个表单项创建</span>
                            <drag-list
                                :showAll="true"
                                :showImg="true"
                                :list="otherTagTypeList"
                                @item-click="handleItemClick"
                            ></drag-list>
                        </div>
<!--                        <div class="creat-node-often">
                            <p class="one">
                                <span class="title">常用表单项</span>
                                <span class="tips" @click="downloadHelpTips"
                                    >使用帮助说明</span
                                >
                            </p>
                            <drag-tag-list
                                @item-click="handleItemClick"
                            ></drag-tag-list>
                        </div>-->
                    </div>
                    <div class="control-canvas-area">
                        <!-- 自定义表单内容 -->
                        <div
                            class="bottom-content"
                            :class="{ isSend: _isSend }"
                        >
                            <div class="bottom-content-header">
                                <el-button
                                    v-if="!_isReadOnly"
                                    class="add-btn"
                                    type="text"
                                    icon="el-icon-plus"
                                    @click="addFormOptions"
                                    >添加自定义表单项</el-button
                                >
                                <el-button
                                    size="mini"
                                    @click="toShowPreview"
                                    v-if="!_isDetail"
                                    >手机端预览</el-button
                                >
                            </div>
                            <drag-tag-form
                                :list.sync="model.items"
                                ref="dragTagFormRef"
                                :checkHasBind="checkHasBind"
                                :deleteBind="deleteBind"
                                @changeNowControl="changeNowControl"
                            >
                            </drag-tag-form>
                        </div>
                    </div>
                    <div class="control-right" v-if="!_isReadOnly">
                        <div
                            class="control-setting-area"
                            :class="{
                                max:
                                    creatNodeNormalHidden &&
                                    creatNodeTypeHidden,
                                showOne:
                                    creatNodeNormalHidden &&
                                    !creatNodeTypeHidden,
                                showTwo:
                                    !creatNodeNormalHidden &&
                                    creatNodeTypeHidden
                            }"
                        >
                            <control-setting
                                :settingControl.sync="settingControl"
                                :list.sync="model.items"
                            ></control-setting>
                        </div>
                    </div>
                </div>
                <footer class="form-main__body-footer">
                    <slot></slot>
                </footer>
            </div>
        </section>
    </main>
</template>

<script lang="ts">
import { Component, Mixins, Prop, Watch } from "vue-property-decorator";
import FormMixin from "@/mixins/form.mixin.ts";
import DragTagList from "../../../components/drag-tag-list/index.vue";
import DragTagForm from "../../../components/drag-tag-form/index.vue";
import SendRange from "../../../components/send-range/index.vue";
import PreviewList from "../../../components/preview/index.vue";
import TreeCascader from "../../../components/tree-cascader/index.vue";
import DragList from "../../../components/drag-tag-list/list.vue";
import ControlSetting from "../../../components/control-setting/index.vue";
import UploadImgGetOptions from "@/views/module-manage/src/components/upload-img-get-options/index.vue";
import { getRandomId } from "@/utils";
import { importResources } from "@/views/module-manage/src/components/import-resources-item/index";
// const mock = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

@Component({
    name: "ModuleManageFormNotAlive",
    components: {
        DragTagList,
        DragTagForm,
        TreeCascader,
        SendRange,
        PreviewList,
        DragList,
        ControlSetting,
        UploadImgGetOptions
    }
})
export default class ModuleManageForm extends Mixins(FormMixin) {
    @Prop({
        type: Object,
        default: () => {
            return {};
        }
    })
    readonly model!: any;

    @Prop({
        type: Object,
        default: () => {
            return {};
        }
    })
    readonly userLevel!: any;

    // @Prop({
    //     type: Array,
    //     default: () => {
    //         return [];
    //     }
    // })
    // readonly tagList!: any[];

    @Prop({
        type: Array,
        default: () => {
            return [];
        }
    })
    readonly departmentList!: any[];

    @Prop({
        type: String,
        default: ""
    })
    readonly formType!: string;

    @Watch("model.items", { immediate: true, deep: true })
    changeModelItems() {
        if (this.settingControl.tempId) {
            const index = this.allItem.findIndex(
                (item: any) => item.tempId === this.settingControl.tempId
            );
            if (index === -1) {
                this.settingControl = {};
            }
        }
    }

    get _isOperation() {
        return ["ADMIN", "OPERATION_ADMIN", "OPERATION"].includes(
            this.userLevel.name
        );
    }

    get _isTownPage() {
        return this.$route.name === "TownModuleManageForm";
    }

    get _isDetail() {
        return this.$route.query.isDetail === "1";
    }

    get _isSend() {
        return this.$route.query.isSend === "send";
    }

    get _isReadOnly() {
        return (
            this.$route.query.isDetail === "1" ||
            this.$route.query.isSend === "send"
        );
    }

    get allItem() {
        const getItem = (arr: any) => {
            let list: any[] = [];
            arr.forEach((item: any) => {
                if (item.itemType === 2) {
                    list.push(item);
                } else {
                    list.push(item);
                    list = list.concat([], getItem(item.items));
                }
            });
            return list;
        };

        return getItem(this.model.items);
    }

    // 当前设置控件
    settingControl: any = {};

    activeCollapse = "formSet";
    otherTagList = [
        {
            id: "importTable"
        },
        {
            id: "importImg"
        },
        {
            id: "Custom_Item",
            name: "批量添加表单项",
            itemType: 2,
            batch: "batch"
        }
        // {
        //     id: "Custom_Item_Resources",
        //     name: "常用资源项",
        //     batch: "resources"
        // }
    ];

    otherTagTypeList = [
        {
            id: "Custom_Item",
            valueKindId: "1",
            value: "input-text",
            name: "单行文本",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "2",
            value: "input-textarea",
            name: "多行文本",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "3",
            value: "input-date",
            name: "日期",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "11",
            value: "input-datetime",
            name: "日期时间",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "4",
            value: "location",
            name: "位置定位",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "6",
            value: "select",
            name: "单选",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "7",
            value: "cascader",
            name: "多选",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "12",
            value: "input-num",
            name: "整数",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "13",
            value: "input-num-decimal",
            name: "小数",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "5",
            value: "upload-img",
            name: "图片",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "8",
            value: "upload-video",
            name: "视频",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "9",
            value: "upload-record",
            name: "录音",
            itemType: 2
        },
        {
            id: "Custom_Item",
            valueKindId: "10",
            value: "upload-file",
            name: "文件",
            itemType: 2
        },
        { id: "Group_Control", name: "分组", value: "group", itemType: 0 },
        { id: "Child_Control", name: "表格", value: "table", itemType: 1 }
    ];

    typeList = [
        { id: "1", value: "input-text", label: "单行文本" },
        { id: "2", value: "input-textarea", label: "多行文本" },
        { id: "3", value: "input-date", label: "日期选择" },
        { id: "11", value: "input-datetime", label: "日期时间选择" },
        { id: "4", value: "location", label: "定位" },
        { id: "6", value: "select", label: "单选" },
        { id: "7", value: "cascader", label: "多选" },
        { id: "12", value: "input-num", label: "整数" },
        { id: "13", value: "input-num-decimal", label: "小数" },
        { id: "5", value: "upload-img", label: "上传图片" },
        { id: "8", value: "upload-video", label: "上传视频" },
        { id: "9", value: "upload-record", label: "上传录音" },
        { id: "10", value: "upload-file", label: "上传文件" }
    ];

    creatNodeTypeHidden = false;
    creatNodeNormalHidden = false;

    mounted() {
        this.initSearchData();
    }

    creatNodeTypeChange() {
        this.creatNodeTypeHidden = !this.creatNodeTypeHidden;
    }

    creatNodeNormalChange() {
        this.creatNodeNormalHidden = !this.creatNodeNormalHidden;
    }

    // 获取表单项类型/单位
    async initSearchData() {
        try {
            const typeResponse = await this.$server["moduleManage/form/type"]({
                loader: false
            });
            if (typeResponse.data.code !== 200) {
                throw typeResponse.data;
            }
            this.typeList = (typeResponse.data.data || []).map((item: any) => {
                return {
                    id: item.id || "",
                    value: item.value || "",
                    label: item.name || ""
                };
            });
        } catch (error) {
            if (error.cancel) {
                return;
            }
            this.$message.error(error.message || "接口请求错误!");
            throw error;
        }
    }

    // 切换当前选中的控件进行设置
    changeNowControl(item: any) {
        this.settingControl = item;
        this.creatNodeTypeHidden = true;
    }

    // 校验是否有绑定显示关系
    checkHasBind(data: any) {
        const index = this.allItem.findIndex(
            (item: any) => item.cascadeId === data.tempId
        );
        return index === -1;
    }

    // 删除绑定关系
    deleteBind(data: any) {
        const id = data.tempId || data.id;
        const getItem = (arr: any) => {
            arr.forEach((item: any) => {
                if (item.itemType === 2) {
                    if (item.cascadeId === id) {
                        item.cascadeId = null;
                        item.cascadeOptionIds = null;
                    }
                } else {
                    getItem(item.items);
                }
            });
        };
        getItem(this.model.items);
    }

    pickerOptions = {
        disabledDate(time: any) {
            const onDay = 1000 * 60 * 60 * 24;
            return time.getTime() < Date.now() - onDay;
        },
        shortcuts: [
            {
                text: "一周内",
                onClick(picker: any) {
                    const end = new Date();
                    const start = new Date();
                    end.setDate(end.getDate() + 6);
                    picker.$emit("pick", [start, end]);
                }
            },
            {
                text: "一个月内",
                onClick(picker: any) {
                    const end = new Date();
                    const start = new Date();
                    end.setMonth(end.getMonth() + 1);
                    picker.$emit("pick", [start, end]);
                }
            },
            {
                text: "三个月内",
                onClick(picker: any) {
                    const end = new Date();
                    const start = new Date();
                    end.setMonth(end.getMonth() + 3);
                    picker.$emit("pick", [start, end]);
                }
            }
        ]
    };

    handleRelationSelectChange(item: any, type: string) {
        let key = "";
        if (type === "tag") {
            key = "tagValue";
        } else {
            key = "departmentValue";
        }
        const _index = this.model[key].findIndex(
            (cur: any) => cur === item.value
        );
        if (_index === -1) {
            this.model[key].push(item.value);
        } else {
            this.model[key].splice(_index, 1);
        }
    }

    async submit() {
        const res = {
            result: false,
            msg: ""
        };
        // const observerRef: any = this.$refs.observerRef;
        // const validateResult: any = await observerRef.validate();
        // if (!validateResult) {
        //     return res;
        // }
        const dragTagFormRef: any = this.$refs.dragTagFormRef;
        const dragTagFormRefValidate: any = dragTagFormRef.submit();
        res.result = dragTagFormRefValidate.result;
        res.msg = dragTagFormRefValidate.msg || "请确保表单数据有效！";
        return res;
    }

    handleItemClick(item: any, type: string, number: number) {
        if (type === "add") {
            const dragTagFormRef: any = this.$refs.dragTagFormRef;
            dragTagFormRef.onAdd(item, number);
        }
    }

    batchAdd(list: any) {
        const dragTagFormRef: any = this.$refs.dragTagFormRef;
        const item = {
            tempId: getRandomId(),
            name: "表单项",
            itemType: 2
        };
        dragTagFormRef.onAdd(item, "", list);
    }

    batchImport(list: any) {
        const itemList: any[] = list.map((item: any) => {
            return {
                ...item,
                options: item.selects
                    ? item.selects.map((cur: any) => {
                        return {
                              id: cur.id,
                              tempId: cur.id,
                              name: cur.name
                        };
                    })
                    : []
            };
        });
        const dragTagFormRef: any = this.$refs.dragTagFormRef;
        dragTagFormRef.onAddImport(itemList);
    }

    importOptions(list: any) {
        const dragTagFormRef: any = this.$refs.dragTagFormRef;
        const item = {
            tempId: getRandomId(),
            name: "表单项",
            itemType: 2
        };
        dragTagFormRef.onAdd(item, "", list);
    }

    // 添加自定义表单项
    addFormOptions() {
        const item = {
            tempId: getRandomId(),
            name: "表单项",
            itemType: 2
        };
        this.handleItemClick(item, "add", 1);
    }

    // 触发预览
    toShowPreview() {
        const clearData = (list: any) => {
            list.forEach((item: any) => {
                item.id = undefined;
                item.unitKindId = item.unitKindId || undefined;
                item.unitKindName = item.unitKindName || undefined;
                item.valueKindId = item.valueKindId || undefined;
                item.valueKindName = undefined;
                item.valueKindValue = undefined;
                item.formId = undefined;
                item.childrenFormId = undefined;
                delete item.itemValue;
                delete item.extData;
                if (item.items && item.items.length) {
                    item.items = clearData(item.items);
                }
            });
            return list;
        };
        this.model.items = clearData(this.model.items);
        this.$emit("toShowPreview");
    }

    // 下载使用说明
    downloadHelpTips() {
        window.open(`${process.env.BASE_URL}export/表单创建使用帮助.pdf`);
    }

    maskShow() {
        importResources({
            sure: (vm: any, model: any) => {
                vm.close();
                this.batchImport(model.selectedList);
            }
        });
    }
}
</script>
